package radio;

import gnu.io.SerialPort;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;

public class RadioInfo extends JFrame {
	/**
	 * Serial Version UID
	 */
	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	private JTextArea textArea;
	private JComboBox comboBox;
	private JButton bSend;
	private JButton bReceive;
	Task task;
	SerialPortHandler port = new SerialPortHandler();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					RadioInfo frame = new RadioInfo();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public RadioInfo() {
		setTitle("Menerima Informasi Dari KA Lain:");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		// Panel
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.NORTH);
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		// List all port
		comboBox = new JComboBox();
		String[] portName = port.getPortNameList();
		for (int i = 0; i < portName.length; i++) {
			comboBox.insertItemAt(portName[i], i);
		}
		comboBox.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent act) {
				try {
					port.connect(comboBox.getSelectedItem().toString(), "KA 101",
							4800, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
							SerialPort.PARITY_NONE, SerialPort.FLOWCONTROL_NONE);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		panel.add(comboBox);

		JScrollPane scrollPane = new JScrollPane();
		contentPane.add(scrollPane, BorderLayout.CENTER);
		// Text box
		textArea = new JTextArea();
		scrollPane.setViewportView(textArea);

		JPanel panel_1 = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel_1.getLayout();
		flowLayout.setAlignment(FlowLayout.RIGHT);
		contentPane.add(panel_1, BorderLayout.SOUTH);
		// Button
		bSend = new JButton("Send");
		bSend.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				task = new Task();
				task.execute();
				bReceive.setEnabled(true);
				bSend.setEnabled(false);
			}
		});
		panel_1.add(bSend);

		bReceive = new JButton("Receive");
		bReceive.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				task = new Task();
				task.execute();
				bSend.setEnabled(true);
				bReceive.setEnabled(false);
			}
		});
		panel_1.add(bReceive);
	}

	class Task extends SwingWorker<Void, Void> {
		@SuppressWarnings("deprecation")
		@Override
		protected Void doInBackground() throws Exception {
			try {
				if (!bReceive.isEnabled()) {
					textArea.setEditable(false);
					InputStream iStream = port.getSerialInputStream();
					byte[] readBuffer = new byte[1024];
					int len = -1;
					while ((len = iStream.read(readBuffer))>-1) {
//						int availableBytes = iStream.available();
							// Read the serial port
						System.out.print(new String(readBuffer,0,len));
//							if (!new String(readBuffer).contains("$")) {
//								textArea.setText(textArea.getText()
//										+ new String(readBuffer));
//							} else {
//								textArea.setText(textArea.getText()
//										+ new String(readBuffer));
//							}
					}
				} else if (!bSend.isEnabled()){
					OutputStream oStream = port.getSerialOutputStream();
					while (true) {
						textArea.setEditable(true);
						String s = textArea.getText();
						byte[] b = new byte[s.length()];
						s.getBytes(0, s.length()-1, b, 0);
						try {
							oStream.write(b);	
							oStream.flush();
						} catch (Exception e) {
							System.err.println(e);
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(null, e.getMessage(),
						"Mengirim dan Menerima Informasi Dari KA Lain:",
						JOptionPane.ERROR_MESSAGE);
			}
			return null;
		}
	}
}
